package cn.com.headfree.base.common;

import java.io.File;
import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;

import cn.com.headfree.file.controller.FileController;

@Component
public class OSSFileClient {
	private static final Logger log = LogManager.getLogger(FileController.class);

	@Value("${oss.bucketName}")
	private String bucketName;
	@Autowired
	private OSSClientFactory oSSClientFactory;

	public OSS getOSSClient() throws InterruptedException {
		OSS ossClient = oSSClientFactory.getOSSClient();
		if (ossClient == null) {
//			log.info(fileName + "队列满了,请稍后重试！");
			return null;
		}
		return ossClient;
	}

	public int upload(String fileName, InputStream is) throws InterruptedException {
		OSS oss = null;
		try {
			oss = this.getOSSClient();
			if (oss == null) {
				return UploadResult.OUT_TIME.getIndex();
			}
			oss.putObject(this.bucketName, fileName, is);
		} finally {
			if (oss != null) {
				try {
					oSSClientFactory.returnOSS(oss);
				} finally {
					oSSClientFactory.initQueue();
				}
			}
		}

		return UploadResult.SUCCESS.getIndex();
	}
	
	public int down(String fileName,File file) throws InterruptedException {
		OSS oss = null;
		try {
			oss = this.getOSSClient();
			if (oss == null) {
				return UploadResult.OUT_TIME.getIndex();
			}
			oss.getObject(new GetObjectRequest(bucketName, fileName), file);
		} finally {
			if (oss != null) {
				try {
					oSSClientFactory.returnOSS(oss);
				} finally {
					oSSClientFactory.initQueue();
				}
			}
		}

		return UploadResult.SUCCESS.getIndex();
	}
	
	public int delete(String fileName) throws InterruptedException {
		OSS oss = null;
		try {
			oss = this.getOSSClient();
			if (oss == null) {
				return UploadResult.OUT_TIME.getIndex();
			}
			oss.deleteObject(bucketName, fileName);
		} finally {
			if (oss != null) {
				try {
					oSSClientFactory.returnOSS(oss);
				} finally {
					oSSClientFactory.initQueue();
				}
			}
		}

		return UploadResult.SUCCESS.getIndex();
	}

}
